package com.gadgets.bm09.controller;

import com.gadgets.bm09.common.Bm09ExceptionCodeConstant;
import com.gadgets.bm09.common.dto.EmcyDataImportDTO;
import com.gadgets.bm09.common.pojo.EcmyMain;
import com.gadgets.bm09.common.pojo.EmcyDataInfo;
import com.gadgets.bm09.process.IEmcyExcelCellProcess;
import com.gadgets.bm09.repository.IEmcyDataInfoRepository;
import com.gadgets.bm09.repository.IMainQueryRepository;
import com.gadgets.framework.common.dto.HttpBaseResp;
import com.gadgets.framework.common.dto.SynergyRedisLock;
import com.gadgets.framework.common.exception.GadgetsServiceException;
import com.gadgets.framework.common.util.ExcelImportUtil;
import com.gadgets.framework.common.util.NumberFormatUtil;
import com.gadgets.framework.common.util.RedisUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.HashMap;

/**
 * 功能说明：
 *
 * @author Unclexiu
 * @version V202101.00.000
 * @data 2022-08-02
 * 修改记录：  修改日期          修改人员    修改说明
 * 2022-08-02  xiujunqing   创建文件
 */
@RestController
@RequestMapping(value = "/emcy")
public class EconomyController {

	protected final Logger logger = LoggerFactory.getLogger(this.getClass());

	private static final HashMap<String, IEmcyExcelCellProcess> processList = new HashMap<>();

	/**
	 * 文件上传基础路径
	 */
	@Value("${spring.uploadPath}")
	private String uploadPath;
	@Value("${spring.downloadPath}")
	private String downloadPath;

	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private IEmcyDataInfoRepository emcyDataInfoRepository;
	@Autowired
	private IMainQueryRepository mainQueryRepository;

	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/dataImport.do")
	public HttpBaseResp importEmcyData(EmcyDataImportDTO importDTO) throws GadgetsServiceException{
		SynergyRedisLock synergyRedisLock = new SynergyRedisLock("/emcy/dataImport.do","120");
		if(redisUtil.setNxSyncLock(synergyRedisLock)){
			try{
				File file = new File(uploadPath+"/"+importDTO.getFileKey()+"."+importDTO.getFileSuffix());
				if(file.exists()) {
					Workbook workbook = ExcelImportUtil.getExcelFile(file, importDTO.getFileSuffix());
					for (Sheet sheet : workbook) {
						int k = 0;
						for (Row cells : sheet) {
							k++;
							logger.info("当前读取第{}行", k);
							if(k<2){
								// 前两行是辅助行，跳过处理
								continue;
							}
							readEmcyData(cells);
						}
					}
				}
			}finally {
				// 解除独占锁定
				redisUtil.deleteSyncLock(synergyRedisLock);
			}
			return new HttpBaseResp();
		}
		throw new GadgetsServiceException(Bm09ExceptionCodeConstant.SYNERGY_LOCK_GET_FAIL, new Object[]{});
	}

	/**
	 * 读取经济数据并保存到数据库
	 * @param cells	数据行
	 */
	protected void readEmcyData(Row cells) {
		// 列计数器
		int j = 0;
		EcmyMain ecmyMain = null;
		for (Cell cell : cells) {
			if(0==j){
				int year = (int)cell.getNumericCellValue();
				if(year!=0) {
					ecmyMain = new EcmyMain();
					ecmyMain.setYear(year);
					mainQueryRepository.insertMainQueryInfo(ecmyMain);
				}
			}else {
				if(null!=ecmyMain) {
					IEmcyExcelCellProcess process = processList.get("column" + NumberFormatUtil.format4Int(j) + "Process");
					if (null != process) {
						EmcyDataInfo dataInfo = process.readProcess(cell, j, ecmyMain);
						emcyDataInfoRepository.insertEmcyDataInfo(dataInfo);
					}
				}
			}
			j++;
		}
	}

	public static void registProcess(String beanName, IEmcyExcelCellProcess process){
		processList.put(beanName, process);
	}

}
